package com.iter.devbox.jsoup;

import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class CityListJsoup {

	String fiveStar = "http://m.api.dianping.com/searchshop.json?start=0&regionid=0&categoryid=3020&sortid=0&locatecityid=2&cityid=2&mylat=1.3553794&mylng=103.86774439999999&_=1469347217937&callback=jsonp3";
	
	String fourStar = "http://m.api.dianping.com/searchshop.json?start=0&regionid=0&categoryid=3022&sortid=0&locatecityid=2&cityid=2&mylat=1.3553794&mylng=103.86774439999999&_=1469347303477&callback=jsonp4";
	//解析网络链接；
	public void parseCityListByURL () {
		
		ExecutorService executorService = Executors.newFixedThreadPool(4);
		CompletionService<String> completionService = new ExecutorCompletionService<String>(executorService);
		
		try {
			String[] cityCatlog = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
			//String[] cityCatlog = {"A"};
			for (int i=0; i<cityCatlog.length; i++) {
				Document doc = Jsoup.connect("http://m.dianping.com/citylist?c="+cityCatlog[i]+"&returl=&type=").get();
				Elements hrefs = doc.select("a[data-id]");
				Iterator<Element> iterator = hrefs.iterator();
				while (iterator.hasNext()) {
					Element element = iterator.next();
					String cityId = element.attr("data-id");
					String cityName = element.text();
					System.out.println(cityId + ":" + cityName);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void parseJson (String json) {
		JSONObject object = JSONObject.fromObject(json);
		JSONArray array = object.getJSONArray("list");
		for (int i=0; i<array.size(); i++) {
			JSONObject jsonObject = array.getJSONObject(i);
			long id = jsonObject.getLong("id");
			String name = jsonObject.getString("name");
			String priceText = jsonObject.getString("priceText");
			System.out.println(id + "--" + name + "--" + priceText);
		}
	}

	public static void main(String[] args) {
		CityListJsoup cityListJsoup = new CityListJsoup();
		cityListJsoup.parseCityListByURL();
		
		String json = "";
	}
}
